package main

import (
	"MySQL_BackUp/Init"
	"fmt"
	"log"
	"os"
	"sync"

	_ "github.com/go-sql-driver/mysql"
)

// 程序入口
func main() {
	//命令行参数 ./xxxx config.yaml <-- yamlFilePath
	if len(os.Args) < 2 {
		fmt.Println("Usage: ./mysql_backup <yaml_file_path>")
		os.Exit(1)
	}
	yamlFilePath := os.Args[1]

	// 初始化服务
	backupService, err := Init.Init(yamlFilePath)
	if err != nil {
		log.Fatalf("Initialization failed: %v", err)
	}
	//延迟关闭数据库
	defer backupService.Db.Close()

	//定义并检查BackupPath、LogPath、BinlogPath路径是否存在
	directories := []string{backupService.Config.BackupPath, backupService.Config.LogPath, backupService.Config.BinlogPath}
	if err := backupService.CheckAndCreateDirectories(directories); err != nil {
		log.Fatalf("Failed to check and create directories: %v", err)
	}

	//检查是否存在备份进程
	if backupService.CheckXtarPid() {
		log.Println("# 备份程序退出~~")
		os.Exit(1)
	}
	var wg sync.WaitGroup
	var mu sync.Mutex

	// 检查磁盘空间
	wg.Add(1)
	go func() {
		defer wg.Done()
		mu.Lock()
		defer mu.Unlock()
		backupService.CheckDevUsage()
	}()

	// 全量备份数据库操作
	wg.Add(1)
	go func() {
		defer wg.Done()
		mu.Lock()
		defer mu.Unlock()
		backupService.BackupDatabase()
	}()

	// 备份 binlog
	wg.Add(1)
	go func() {
		defer wg.Done()
		mu.Lock()
		defer mu.Unlock()
		backupService.BackupBinlog()
	}()

	// 等待所有 goroutine 完成
	wg.Wait()

	log.Println("# 所有备份任务完成")
}
